/*
 * Created on 2007. svibanj 12, 01:11
 */

package hr.ctg.service;

import hr.ctg.SystemException;
import hr.ctg.domain.model.VrijednostValute;
import hr.ctg.service.dao.ValutaDAO;
import hr.ctg.service.dao.VrijednostValuteDAO;
import hr.ctg.service.work.Work;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.annotations.async.Asynchronous;
import org.jboss.seam.annotations.async.Expiration;
import org.jboss.seam.annotations.async.IntervalDuration;

/**
 * 
 * @author ivica
 * @version
 */
@Name("exchangeRateService")
public class ExchangeRateService implements Work {
	private static final String exchangeListURL = "http://www.hnb.hr/tecajn/f<date>.dat";

	@In
	VrijednostValuteDAO vrijednostValuteDAO;
	@In
	ValutaDAO valutaDAO;

	/**
	 * @return
	 */
	@Factory(value = "currencies")
	public List<VrijednostValute> getCurrencies() {
		List<VrijednostValute> currencies = vrijednostValuteDAO.findLast();
		VrijednostValute euro = null;
		for(VrijednostValute vv:currencies){
			if("EUR".equals(vv.getValuta().getOznaka())){
				euro = vv;
				break;
			}
		}
		// safty check
		if(null!=euro){
			currencies.remove(euro);
			currencies.add(0,euro);
		}
		return currencies;
	}

	@Asynchronous
	@Transactional
	public void process(@Expiration final Date exp,
			@IntervalDuration final long duration) {
		process();
	}

	@Override
	@Asynchronous
	@Transactional
	public void process(Date date) {
		process();
	}

	private void process() {
		java.io.BufferedReader br = null;

		org.joda.time.DateTime dt = new org.joda.time.DateTime();
		// lista za trenutni dan je objavljena dan ranije
		// dt = dt.minusDays(1);
		boolean fileExists = false;
		String date = null;
		while (!fileExists) {
			try {
				date = dt.toString(org.joda.time.format.DateTimeFormat
						.forPattern("ddMMyy"));
				final java.net.URL url = new java.net.URL(exchangeListURL
						.replace("<date>", date));
				final InputStream stream = url.openStream();
				stream.close();
				fileExists = true;
			} catch (final IOException e) {
				dt = dt.minusDays(1);
			}
		}
		if (vrijednostValuteDAO.findByDatum(dt.toDateMidnight().toDate())
				.size() > 0) {
			return;
		} else {
			try {
				java.net.URL url = new java.net.URL(exchangeListURL.replace(
						"<date>", date));
				try {
					br = new java.io.BufferedReader(
							new java.io.InputStreamReader(url.openStream()));
				} catch (final FileNotFoundException ex) {
					// vikend
					dt = dt.minusDays(1);
					date = dt.toString(org.joda.time.format.DateTimeFormat
							.forPattern("ddMMyy"));
					if (vrijednostValuteDAO.findByDatum(
							dt.toDateMidnight().toDate()).size() > 0) {
						return;
					}
					url = new java.net.URL(exchangeListURL.replace("<date>",
							date));
					try {
						br = new java.io.BufferedReader(
								new java.io.InputStreamReader(url.openStream()));
					} catch (final FileNotFoundException e) {
						dt = dt.minusDays(1);
						date = dt.toString(org.joda.time.format.DateTimeFormat
								.forPattern("ddMMyy"));
						if (vrijednostValuteDAO.findByDatum(
								dt.toDateMidnight().toDate()).size() > 0) {
							return;
						}
						url = new java.net.URL(exchangeListURL.replace(
								"<date>", date));
						br = new java.io.BufferedReader(
								new java.io.InputStreamReader(url.openStream()));
					}
				}

				br.readLine();
				java.lang.String line;

				while ((line = br.readLine()) != null) {
					final java.util.Scanner sc = new java.util.Scanner(line);
					final VrijednostValute vv = new VrijednostValute();
					final String column = sc.next();
					vv.setDatum(dt.toDate());
					vv.setValuta(valutaDAO.find(Integer
							.parseInt(new java.util.Scanner(column)
									.findInLine(java.util.regex.Pattern
											.compile("[0-9][0-9][0-9]")))));
					// m
					// .put("unit", new java.util.Scanner(column).skip(
					// "[0-9][0-9][0-9]").findInLine(
					// java.util.regex.Pattern
					// .compile("[0-9][0-9][0-9]")));
					vv.setKupnja(Float.parseFloat(sc.next().replace(",", ".")));
					vv
							.setSrednji(Float.parseFloat(sc.next().replace(",",
									".")));
					vv
							.setProdaja(Float.parseFloat(sc.next().replace(",",
									".")));

					vrijednostValuteDAO.persist(vv);
				}
			} catch (final IOException ex) {
				Logger.getLogger(ExchangeRateService.class.getName()).log(
						Level.SEVERE, null, ex);
				throw new SystemException(ex);
			} finally {
				try {
					if (br != null) {
						br.close();
					}
				} catch (final IOException ex) {
					Logger.getLogger(ExchangeRateService.class.getName()).log(
							Level.SEVERE, null, ex);
				}
			}
		}
	}
}
